package com.imddy.spbatch001.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Random;

public class RandomCSVGenerator {
    private static final Logger log = LoggerFactory.getLogger(RandomCSVGenerator.class);

    private static final Random random = new Random();
    private static final Random randomcc = new Random();

    // 随机文本数据池
    private static final String[] FIRST_NAMES = {
            "张三", "李四", "王五", "赵六", "陈七", "刘八", "杨九", "黄十",
            "周一", "吴二", "郑三", "王四", "冯五", "陈六", "褚七", "卫八"
    };

    private static final String[] LAST_NAMES = {
            "明", "华", "强", "伟", "芳", "娜", "敏", "静", "丽", "军",
            "磊", "洋", "勇", "艳", "杰", "涛", "超", "娟", "霞", "平"
    };

    private static final String[] CITIES = {
            "北京", "上海", "广州", "深圳", "杭州", "南京", "武汉", "成都",
            "西安", "重庆", "天津", "苏州", "长沙", "郑州", "青岛", "大连"
    };

    private static final String[] COMPANIES = {
            "阿里巴巴", "腾讯", "百度", "京东", "美团", "字节跳动", "滴滴",
            "小米", "华为", "网易", "新浪", "搜狐", "360公司", "携程", "爱奇艺"
    };

    private static final String[] PRODUCTS = {
            "苹果", "香蕉", "橙子", "葡萄", "西瓜", "草莓", "猕猴桃", "芒果",
            "笔记本电脑", "手机", "平板", "耳机", "键盘", "鼠标", "显示器", "音响"
    };

    /**
     * 数据类型枚举
     */
    public enum DataType {
        TEXT,           // 随机文本
        INTEGER,        // 随机整数
        DECIMAL,        // 随机小数
        NAME,           // 随机姓名
        CITY,           // 随机城市
        COMPANY,        // 随机公司
        PRODUCT,        // 随机产品
        EMAIL,          // 随机邮箱
        PHONE,          // 随机电话
        DATE,           // 随机日期
        URL,            // 随机URL
        BOOLEAN         // 随机布尔值
    }

    /**
     * 列定义类
     */
    public static class ColumnDefinition {
        private String columnName;
        private DataType dataType;
        private int minValue = 0;      // 对于整数和小数的最小值
        private int maxValue = 100;    // 对于整数和小数的最大值
        private int decimalPlaces = 2; // 小数位数

        public ColumnDefinition(String columnName, DataType dataType) {
            this.columnName = columnName;
            this.dataType = dataType;
        }

        public ColumnDefinition(String columnName, DataType dataType, int minValue, int maxValue) {
            this.columnName = columnName;
            this.dataType = dataType;
            this.minValue = minValue;
            this.maxValue = maxValue;
        }

        public ColumnDefinition(String columnName, DataType dataType, int minValue, int maxValue, int decimalPlaces) {
            this.columnName = columnName;
            this.dataType = dataType;
            this.minValue = minValue;
            this.maxValue = maxValue;
            this.decimalPlaces = decimalPlaces;
        }

        // Getters
        public String getColumnName() { return columnName; }
        public DataType getDataType() { return dataType; }
        public int getMinValue() { return minValue; }
        public int getMaxValue() { return maxValue; }
        public int getDecimalPlaces() { return decimalPlaces; }
    }

    /**
     * 生成随机CSV文件的主方法
     * @param filePath 文件路径
     * @param rowCount 数据行数（不包括表头）
     * @param columnDefinitions 列定义数组
     * @throws IOException 文件操作异常
     */
    public static void generateRandomCSV(String filePath, int rowCount, ColumnDefinition[] columnDefinitions) throws IOException {
        if (columnDefinitions == null || columnDefinitions.length == 0) {
            throw new IllegalArgumentException("列定义不能为空");
        }

        FileWriter writer = null;
        try {
            writer = new FileWriter(filePath, StandardCharsets.UTF_8);

            // 写入表头
            for (int i = 0; i < columnDefinitions.length; i++) {
                if (i > 0) writer.write(",");
                writer.write(escapeCSVField(columnDefinitions[i].getColumnName()));
            }
            writer.write("\n");

            // 写入数据行
            for (int row = 0; row < rowCount; row++) {
                for (int col = 0; col < columnDefinitions.length; col++) {
                    if (col > 0) writer.write(",");
                    String value = generateRandomValue(columnDefinitions[col]);
                    writer.write(escapeCSVField(value));
                }
                writer.write("\n");
            }

        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 简化版本：快速生成随机CSV
     * @param filePath 文件路径
     * @param rowCount 行数
     * @param columnCount 列数
     * @param dataTypes 每列的数据类型（如果为null，则随机选择类型）
     */
    public static void generateQuickRandomCSV(String filePath, int rowCount, int columnCount, DataType[] dataTypes) throws IOException {
        ColumnDefinition[] columns = new ColumnDefinition[columnCount];

        for (int i = 0; i < columnCount; i++) {
            DataType type = (dataTypes != null && i < dataTypes.length) ?
                    dataTypes[i] : DataType.values()[random.nextInt(DataType.values().length)];
            columns[i] = new ColumnDefinition("列" + (i + 1), type);
        }

        generateRandomCSV(filePath, rowCount, columns);
    }

    /**
     * 最简版本：完全随机生成
     */
    public static void generateFullRandomCSV(String filePath, int rowCount, int columnCount) throws IOException {
        generateQuickRandomCSV(filePath, rowCount, columnCount, null);
    }

    /**
     * 根据列定义生成随机值
     */
    private static String generateRandomValue(ColumnDefinition column) {
        switch (column.getDataType()) {
            case TEXT:
                //return generateRandomText();
                return generateRandomChinese(column.getMinValue(), column.getMaxValue());
            case INTEGER:
                return String.valueOf(random.nextInt(column.getMaxValue() - column.getMinValue() + 1) + column.getMinValue());
            case DECIMAL:
                double value = column.getMinValue() + (column.getMaxValue() - column.getMinValue()) * random.nextDouble();
                return String.format("%." + column.getDecimalPlaces() + "f", value);
            case NAME:
                return FIRST_NAMES[random.nextInt(FIRST_NAMES.length)] + LAST_NAMES[random.nextInt(LAST_NAMES.length)];
            case CITY:
                return CITIES[random.nextInt(CITIES.length)];
            case COMPANY:
                return COMPANIES[random.nextInt(COMPANIES.length)];
            case PRODUCT:
                return PRODUCTS[random.nextInt(PRODUCTS.length)];
            case EMAIL:
                return generateRandomEmail();
            case PHONE:
                return generateRandomPhone();
            case DATE:
                return generateRandomDate();
            case URL:
                return generateRandomURL();
            case BOOLEAN:
                return random.nextBoolean() ? "是" : "否";
            default:
                //return generateRandomText();
                return generateRandomChinese(column.getMinValue(), column.getMaxValue());
        }
    }

    /**
     * 生成随机文本
     */
    private static String generateRandomText() {
        String[] words = {"数据", "信息", "系统", "管理", "服务", "平台", "技术", "开发", "测试", "产品"};
        return words[random.nextInt(words.length)] + (random.nextInt(999) + 1);
    }
    public static String generateRandomChineseChar() {
        String sbase="的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后";
        int i = randomcc.nextInt(sbase.length());
        return String.valueOf(sbase.charAt(i));
    }
    public static String generateRandomChinese(int length) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < length; i++) {
            result.append(generateRandomChineseChar());
        }
        return result.toString();
    }
    public static String generateRandomChinese(int minLength, int maxLength) {
        int length = minLength + random.nextInt(maxLength - minLength + 1);
        return generateRandomChinese(length);
    }

    /**
     * 生成随机邮箱
     */
    private static String generateRandomEmail() {
        String[] domains = {"gmail.com", "163.com", "qq.com", "sina.com", "hotmail.com"};
        String username = "user" + (random.nextInt(9999) + 1);
        return username + "@" + domains[random.nextInt(domains.length)];
    }

    /**
     * 生成随机电话号码
     */
    private static String generateRandomPhone() {
        return "1" + (3 + random.nextInt(6)) + String.format("%09d", random.nextInt(1000000000));
    }

    /**
     * 生成随机日期
     */
    private static String generateRandomDate() {
        int year = 2020 + random.nextInt(5);
        int month = 1 + random.nextInt(12);
        int day = 1 + random.nextInt(28);
        return String.format("%04d-%02d-%02d", year, month, day);
    }

    /**
     * 生成随机URL
     */
    private static String generateRandomURL() {
        return "https://" + "www." + "example." + "com" + "/" + "page" + (random.nextInt(99999) + 1);
    }

    /**
     * CSV字段转义
     */
    private static String escapeCSVField(String field) {
        if (field == null) return "";

        if (field.contains(",") || field.contains("\"") || field.contains("\n") || field.contains("\r")) {
            field = field.replace("\"", "\"\"");
            return "\"" + field + "\"";
        }
        return field;
    }









    public static void main(String[] args) {
//        try {
//            System.out.println("test001()...");
//            test001();
//            System.out.println("test001()执行完成！");
//        } catch (IOException e) {
//            System.out.println("test001()发生异常");
//            e.printStackTrace();
//        }
//
//
//        try {
//            System.out.println("test002()...");
//            test002();
//            System.out.println("test002()执行完成！");
//        } catch (IOException e) {
//            System.out.println("test002()发生异常");
//            e.printStackTrace();
//        }
//
//
//        try {
//            System.out.println("test003()...");
//            test003();
//            System.out.println("test003()执行完成！");
//        } catch (IOException e) {
//            System.out.println("test003()发生异常");
//            e.printStackTrace();
//        }
//
//
//        try {
//            System.out.println("test004()...");
//            test004();
//            System.out.println("test004()执行完成！");
//        } catch (IOException e) {
//            System.out.println("test004()发生异常");
//            e.printStackTrace();
//        }

        try {
            System.out.println("test005()...");
            test005();
            System.out.println("test005()执行完成！");
        } catch (IOException e) {
            System.out.println("test005()发生异常");
            e.printStackTrace();
        }
    }


    public static void test001() throws IOException {
        // 示例1：自定义列定义
        RandomCSVGenerator.ColumnDefinition[] columns = {
                new RandomCSVGenerator.ColumnDefinition("姓名", RandomCSVGenerator.DataType.NAME),
                new RandomCSVGenerator.ColumnDefinition("年龄", RandomCSVGenerator.DataType.INTEGER, 18, 65),
                new RandomCSVGenerator.ColumnDefinition("工资", RandomCSVGenerator.DataType.DECIMAL, 3000, 50000, 2),
                new RandomCSVGenerator.ColumnDefinition("城市", RandomCSVGenerator.DataType.CITY),
                new RandomCSVGenerator.ColumnDefinition("邮箱", RandomCSVGenerator.DataType.EMAIL),
                new RandomCSVGenerator.ColumnDefinition("电话", RandomCSVGenerator.DataType.PHONE),
                new RandomCSVGenerator.ColumnDefinition("入职日期", RandomCSVGenerator.DataType.DATE),
                new RandomCSVGenerator.ColumnDefinition("是否在职", RandomCSVGenerator.DataType.BOOLEAN)
        };

        RandomCSVGenerator.generateRandomCSV("employees.csv", 1000, columns);
        System.out.println("员工数据CSV生成成功：1000行数据");
    }


    public static void test002() throws IOException {
        // 示例2：指定数据类型的快速生成
        RandomCSVGenerator.DataType[] types = {
                RandomCSVGenerator.DataType.PRODUCT,
                RandomCSVGenerator.DataType.DECIMAL,
                RandomCSVGenerator.DataType.INTEGER,
                RandomCSVGenerator.DataType.COMPANY,
                RandomCSVGenerator.DataType.BOOLEAN
        };

        RandomCSVGenerator.generateQuickRandomCSV("products.csv", 500, 5, types);
        System.out.println("产品数据CSV生成成功：500行5列");
    }


    public static void test003() throws IOException {
        // 示例3：完全随机生成
        RandomCSVGenerator.generateFullRandomCSV("random_data.csv", 2000, 10);
        System.out.println("随机数据CSV生成成功：2000行10列");
    }


    public static void test004() throws IOException {
        // 示例4：指定数据类型的快速生成
        RandomCSVGenerator.DataType[] types = {
                RandomCSVGenerator.DataType.PRODUCT,
                RandomCSVGenerator.DataType.DECIMAL,
                RandomCSVGenerator.DataType.INTEGER,
                RandomCSVGenerator.DataType.COMPANY,
                RandomCSVGenerator.DataType.BOOLEAN,
                RandomCSVGenerator.DataType.TEXT
        };

        RandomCSVGenerator.generateQuickRandomCSV("products6.csv", 500, 6, types);
        System.out.println("产品数据CSV生成成功：500行6列");
    }


    public static void test005() throws IOException {
        // 示例5：指定数据类型的快速生成
        RandomCSVGenerator.ColumnDefinition[] columns = {
                new RandomCSVGenerator.ColumnDefinition("姓名", RandomCSVGenerator.DataType.NAME),
                new RandomCSVGenerator.ColumnDefinition("URL", DataType.URL),
                new RandomCSVGenerator.ColumnDefinition("标题", DataType.TEXT, 3, 15),
                new RandomCSVGenerator.ColumnDefinition("内容", DataType.TEXT, 20, 50),
        };

        RandomCSVGenerator.generateRandomCSV("test005.csv", 500000, columns);
        System.out.println("产品数据CSV生成成功：500000行005列");
    }

}
